package com.learn.springbootcache.config;


import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import sun.java2d.DisposerRecord;

import java.io.IOException;

/**
 * @author jiaomingyu5778@gmail.com
 * @date 2019/10/24 23:28
 */
@Component
public class ElasticsearchClient implements DisposerRecord {

    private RestHighLevelClient client;

    private final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    @Bean
    public RestHighLevelClient getRestHighLevelClient() {
//        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("", ""));
        client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9200, "http"))
                        .setHttpClientConfigCallback(httpAsyncClientBuilder -> {
                            //这里可以设置一些参数，比如cookie存储、代理等等
                            httpAsyncClientBuilder.disableAuthCaching();
                            return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                        })
        );

        return client;
    }

    @Override
    public void dispose() {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
